package thread;

import thread.MyCallable;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class CallableExample {
    public static void main(String[] args) {
        // 创建线程池
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 创建Callable任务
        Callable<String> task1 = new MyCallable("任务1", 5);
        Callable<String> task2 = new MyCallable("任务2", 3);

        // 提交任务并获取Future对象
        Future<String> future1 = executor.submit(task1);
        Future<String> future2 = executor.submit(task2);

        System.out.println("任务已提交，等待结果...");

        try {
            // 获取任务执行结果（会阻塞直到任务完成）
            String result1 = future1.get();
            String result2 = future2.get();

            System.out.println("任务1结果: " + result1);
            System.out.println("任务2结果: " + result2);
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            executor.shutdown();
            System.out.println("线程池已关闭");
        }
    }
}